package com.jysz.struts2.components;
/**
 *
 * @author xuxiaolong
 */
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.components.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jysz.certificate.constant.OperCodeConstant;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.RoleService;
import com.jysz.certificate.utils.CommonUtil;
import com.opensymphony.xwork2.util.ValueStack;
  
public class PermissionComponent extends Component {   
  
    private RoleService roleService;   
    private String code;   
    private User user;
       
    public PermissionComponent(ValueStack stack, HttpServletRequest request) {   
        super(stack);   
        this.setRoleService(request);   
    }   
  
    @Override  
    public boolean start(Writer writer) {  
    	
    	boolean result=false;
    	if(user!=null&&user.getPost().compareTo(PostType.Admin)==0)
    		return true;
    	if(this.user!=null&&roleService!=null&&CommonUtil.isNotEmpty(code)){
    		try {
    			Class c=OperCodeConstant.class;
				code=c.getDeclaredField(code).get(c).toString();
			} catch (Exception e) {
				code=null;
			}
    		if(code!=null)
    			result=roleService.checkPermission(this.user, code);
    	}
        return result;   
    }   
  
    @Override  
    public boolean end(Writer writer, String body) {   
        return super.end(writer, body);   
    }   
  
    public void setRoleService(RoleService roleService) {   
        this.roleService = roleService;   
    }   
  
    public void setRoleService(HttpServletRequest request) {   
  
        WebApplicationContext wac = WebApplicationContextUtils   
                .getRequiredWebApplicationContext(request.getSession()   
                        .getServletContext());   
  
        this.roleService = (RoleService) wac.getBean("roleService");
        Object obj=request.getSession().getAttribute("loginSession");
        if(obj!=null)
        	this.user=(User) obj;
    }

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}  
  
}  